package com.example.webapi.controller;


import cn.hutool.json.JSONObject;
import cn.hutool.setting.Setting;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.webapi.Utils.ResponseModel;
import com.example.webapi.entity.Resultstate;
import com.example.webapi.json.jsonUtils;
import com.example.webapi.service.ResultstateService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("Project")
public class apiCOntroller {
    @Resource
    ResultstateService resultstateService;
    private static final Logger logger = LogManager.getLogger(jsonUtils.class);

    public static void checkProject(String projectNumber,String filePath) {

        Setting setting = new Setting("config/project.setting");
        String exePath = setting.getStr("exePath");

        final String[] exepaparm = new String[7];
        exepaparm[0] = "cmd";
        exepaparm[1] = "/c";
        exepaparm[2] = exePath;
        exepaparm[3] = "-m";
        exepaparm[4] = projectNumber;
        exepaparm[5] = "-n";
        exepaparm[6] = filePath;
        try {
            //用Process调用 开始检测
            //pBuilder.start();
            Thread worker = new Thread() {
                public void run() {
                    startExe(exepaparm);
                }
            };
            worker.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void startExe(String[] exepaparm) {
        logger.info("进入startExe函数");
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            logger.info(exepaparm);
            logger.info("执行");
            Process process = Runtime.getRuntime().exec(exepaparm);
            process.getOutputStream().close();

            is = process.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                isr.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //威海项目演示
    @PostMapping("putParams")
    public ResponseModel putParams(@RequestBody JSONObject data){
        logger.info(data.getStr("projectNumber"));
        // 先删除
        resultstateService.remove(new QueryWrapper<Resultstate>().eq("projectNumber",data.getStr("projectNumber")));

        String projectNumber = data.getStr("projectNumber");
        String filePath = data.getStr("filePath").replace("//","");
        checkProject(projectNumber,filePath);
        return ResponseModel.success("请求exe成功");
    }
    /**
     * 计算完毕后回调
     */
    @GetMapping("projectCallback")
    public ResponseModel projectCallback(String prjSid, String state){
        logger.info("C++回调我了"+prjSid);
        Resultstate resultstate = new Resultstate();
        if (!state.equals("136")){
            // exe调用完毕数据库记录
            resultstate.setProjectNumber(prjSid);
            resultstate.setState("0");
            resultstateService.save(resultstate);
            //读取classpath下的XXX.setting，不使用变量
            Setting setting = new Setting("config/project.setting");
            String baseDIR = setting.getStr("baseDIR");
            String jonBaseDir = baseDIR + "/" + prjSid + "/" + "ModelAndProp";

            String fileName = setting.getStr("fileName");
            String url = setting.getStr("url");
            Map<String,Object> map = new HashMap<>();
            jsonUtils.findFiles(jonBaseDir,fileName,map,url,prjSid);
            return ResponseModel.success("数据已推送");
        }else{
            return ResponseModel.fail("数据错误");
        }

    }

    /**
     * 获取状态接口
     * @return
     */
    @GetMapping("getState")
    public ResponseModel getState(@RequestParam String projectNumber) {
        Resultstate resultstate = resultstateService.getOne(new QueryWrapper<Resultstate>().eq("projectNumber",projectNumber));
        Map<String,Object> map = new HashMap<>();
        map.put("projectNumber",projectNumber);
        if (resultstate == null){
            return ResponseModel.fail("数据不存在");
        }
        if (resultstate.getState().equals("0")){
            return ResponseModel.success(map,"数据审查完毕");
        }else{
            return ResponseModel.fail("电子报批发生错误");
        }
    }
}
